package com.jfirer.mvc.resolver.impl;

import com.jfirer.baseutil.StringUtil;
import com.jfirer.baseutil.reflect.ReflectUtil;
import com.jfirer.mvc.annotation.CookieValue;
import com.jfirer.mvc.resolver.AbstractParamResolver;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieResolver extends AbstractParamResolver
{
    private final String cookieName;
    private final String defaultValue;

    private Class type;

    public CookieResolver(Class<?> ckass, String paramName, CookieValue cookieValue)
    {
        super(paramName);
        String cookieName   = cookieValue.value();
        String defaultValue = cookieValue.defaultValue();
        if (cookieName.equals(""))
        {
            cookieName = paramName;
        }
        if (defaultValue.equals(""))
        {
            defaultValue = null;
        }
        this.cookieName = cookieName;
        this.defaultValue = defaultValue;
        if (ckass.isPrimitive())
        {
            type = ReflectUtil.wrapPrimitive(ckass);
        }
        else
        {
            type = ckass;
        }
    }

    @Override
    public Object resolve(HttpServletRequest request, HttpServletResponse response)
    {
        Cookie[] cookies = request.getCookies();
        Cookie   target  = null;
        for (Cookie each : cookies)
        {
            if (each.getName().equals(cookieName))
            {
                target = each;
                break;
            }
        }
        String value = target != null ? target.getValue() : StringUtil.isNotBlank(defaultValue) ? defaultValue : null;
        if (value == null)
        {
            return null;
        }
        return toValue(type, value);
    }
}
